<?php
declare(strict_types=1);

namespace app\admin\model;

use app\common\support\Password;
use think\model\concern\SoftDelete;

class AdminSettings extends Base
{
    use SoftDelete;

    protected $name = 'system_admin_settings';
    // 设置json类型字段
    protected $json = ['system_theme_setting'];
    /**
     * 角色
     * @return \think\model\relation\BelongsTo
     */
    public function admin(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(Admin::class, 'id', 'admin_id');
    }

    /**
     * 创建前
     *
     * @param Admin $model
     *
     * @return mixed|void
     */
    public static function onBeforeInsert($model)
    {
        parent::onBeforeInsert($model);
        $model->id = md5(mt_rand(100000, 999999) . microtime());
        $model->create_ip = request()->ip();
        $model->create_time = time();
        $model->last_active = time();
        $model->last_ip = request()->ip();
    }

    /**
     * 更新前
     *
     * @param Admin $model
     *
     * @return mixed|void
     */
    public static function onBeforeUpdate($model)
    {
        parent::onBeforeUpdate($model);
        $model->last_active = time();
        $model->last_ip = request()->ip();
    }


    public static function getUserSettings($userId)
    {
        $AdminSettings = self::field('system_theme_setting')
            ->where('admin_id', $userId)
            ->value('system_theme_setting');
        return json_decode($AdminSettings, true) ?? [];
    }
    public static function setUserSettings($userId, array $data)
    {
        $system_theme_setting = json_encode($data['system_theme_setting'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        $AdminSettings = self::where('admin_id', $userId)->findOrEmpty();
        if ($AdminSettings) {
            $AdminSettings->admin_id = $userId;
            $AdminSettings->system_theme_setting = $system_theme_setting;
            $AdminSettings->save();
        } else {
            self::create($data);
            $data['admin_id'] = $userId;
            $AdminSettings->system_theme_setting = $system_theme_setting;
            $AdminSettings->save();
        }
        return true;
    }
}
